package stock;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.hibernate.Session;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Component
@SuppressWarnings("all")
public class StockQQService implements StockQQServiceInterface {

	@Override
	@Transactional
	@Scheduled(cron = "0 20 15 * * ?")
	public void getStockQQ() {

		LocalDate today = LocalDate.now();

		// 判断今天是否是周六或周日
		boolean isWeekend = today.getDayOfWeek() == DayOfWeek.SATURDAY || today.getDayOfWeek() == DayOfWeek.SUNDAY;
		if (isWeekend == true) {
			return;
		}

		System.out.println("加载每日QQ数据");

		String sql = "select DISTINCT(code),name,diqv from stock ";
		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<String[]> list = session1.createSQLQuery(sql).list();
		List<String> lists = new ArrayList<String>();
		String all = "";
		for (int i = 0; i < list.size(); i++) {
			Object[] json = list.get(i);
			String code = json[0] + "";
			String name = json[1] + "";
			String diqv = json[2] + "";
			if ("0".equals(diqv)) {
				code = "sh" + code;
			} else {
				code = "sz" + code;
			}
			if (i % 500 == 0 && i != 0) {
				all += code + "";
				// System.out.println(all);
				lists.add(all);
				all = "";
				continue;
			}
			if (i == list.size() - 1) {
				// all += code + "";
				// System.out.println(all);
				lists.add(all);
				break;
			}
			all += code + ",";
		}
		JSONArray jsonall = new JSONArray();
		for (int i = 0; i < lists.size(); i++) {
			JSONArray jsona = getCcc(lists.get(i));
			jsonall.addAll(jsona);
		}
		System.out.println("总长为：" + jsonall.size());
		// String sql1 = "select * from stockqq t where t.date = ?0 and t.code = ?1";
		String sql2 = "delete from stockqq where date =  " + DateTools.getCurrentDate("yyyyMMdd");
		session1.getTransaction().begin();
		session1.createSQLQuery(sql2).executeUpdate();
		session1.getTransaction().commit();
		session1.clear();
		int xc = 20;
		int temp = jsonall.size() / xc;
		Thread[] threads = new Thread[20];
		for (int i = 0; i < xc; i++) {
			Thread t = null;
			if (i == xc - 1) {
				t = new Thread(new StockQQRunable(jsonall, i * temp, jsonall.size()));
			} else {
				t = new Thread(new StockQQRunable(jsonall, i * temp, i * temp + temp));
			}
			threads[i] = t;
			t.start();
		}

		for (Thread thread : threads) {
			try {
				thread.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public JSONArray getCcc(String codearr) {

		JSONArray jsonarrr = new JSONArray();
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet("http://qt.gtimg.cn/q=" + codearr);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String[] arary = codearr.split(",");
		try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String responseData = EntityUtils.toString(entity);
				// 对返回的responseData进行处理
				String[] str = responseData.split(";");
				for (int i = 0; i < str.length; i++) {
					String[] str1 = str[i].split("~");
					if (str1.length <= 1) {
						continue;
					}
					JSONObject json = new JSONObject();
					json.put("name", str1[1]);
					json.put("dqj", str1[3]);
					json.put("code", str1[2]);
					json.put("zhangdiefu", str1[32]);
					json.put("zuigao", str1[33]);
					json.put("zuidi", str1[34]);
					json.put("huanshoulv", str1[38]);
					json.put("cjje", str1[37]);
					json.put("shizhi", str1[45]);
					json.put("date", str1[30].substring(0, 8));
					jsonarrr.add(json);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return jsonarrr;
	}

	@Scheduled(cron = "0 32 16 * * ?")
	@Override
	public void getStockQQzTCentent() {
		// TODO Auto-generated method stub

		// 获取当前日期
		Calendar calendar = Calendar.getInstance();

		// 将日期往前推 20 天
		calendar.add(Calendar.DAY_OF_MONTH, -20);

		// 获取前 20 天的日期
		Date twentyDaysAgo = calendar.getTime();

		// 设置日期格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

		// 输出前 20 天的日期
		String day = sdf.format(twentyDaysAgo);

		String sql = "select zt_note from stockqq t where t.zt_note <> '' and t.date > " + day;

		Session session1 = ContextUtil.getSessionFactory1().openSession();
		List<String> list0 = session1.createSQLQuery(sql).list();
		List<String> inputList = new ArrayList<String>();

		for (int i = 0; i < list0.size(); i++) {

			String str = list0.get(i).replaceAll("+", "-");
			String[] arr = str.split("-");
			for (int j = 0; j < arr.length; j++) {
				inputList.add(arr[j]);
			}
		}

		session1.close();

		// 统计相同字符串的数量
		Map<String, Integer> countMap = new HashMap<>();
		for (String item : inputList) {
			if (countMap.containsKey(item)) {
				countMap.put(item, countMap.get(item) + 1);
			} else {
				countMap.put(item, 1);
			}
		}

		// 对结果进行降序排序
		List<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(countMap.entrySet());
		sortedEntries.sort(new Comparator<Map.Entry<String, Integer>>()
		{
			@Override
			public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}
		});

		// 打印排序后的结果
		for (Map.Entry<String, Integer> entry : sortedEntries) {
			System.out.println(entry.getKey() + ": " + entry.getValue());
		}

	}
}
